package com.lijianlove.message.service.processor;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.lijianlove.message.common.enums.MsgStatusEnum;
import com.lijianlove.message.common.model.Message;
import com.lijianlove.message.dal.MessageStoreService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessageListener;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.rabbit.listener.adapter.AbstractAdaptableMessageListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * @author lijian
 * @date 2019/5/29 下午5:19
 */
@Slf4j
@Component
public class AbstractMessageProcessor {

    @Autowired
    private MessageStoreService messageStoreService;

    public MsgStatusEnum process(org.springframework.amqp.core.Message message, Map<String, Object> headers, Channel channel) {
        log.info("--------------收到消息，开始消费------------");

        Message msg = JSONObject.parseObject(new String(message.getBody()), Message.class);

        log.info("msg {}", message);

        if (msg == null) {
            return null;
        }
        // ready 状态的消息只消费不处理
        if (msg.getStatus().getValue().equals(MsgStatusEnum.INIT.getValue())) {

        }

        Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        // ACK
        try {
            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {
            log.error("channel.basicAck error msg {},headers {} , channel {} ", msg, headers, channel, e);
        }


        return msg.getStatus();
    }

    @RabbitListener(queues = "queue-dt")
    @RabbitHandler
    public void onOrderMessage(@Payload org.springframework.amqp.core.Message msg, @Headers Map<String, Object> headers, Channel channel) {
        process(msg, headers, channel);
    }


    public void consume(Message msg){

    }
}
